package fischl.web;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import fi.iki.elonen.NanoHTTPD;

import static fi.iki.elonen.NanoHTTPD.*;

public class StaticResourceHandler implements RouteHandler {
  private Set<String> staticPaths;


  @Override
  public NanoHTTPD.Response handle(NanoHTTPD.IHTTPSession session) {
//    if (staticPaths == null) {
//      try {
//        String[] children = context.getAssets().list("static");
//        staticPaths = new HashSet<>(children.length);
//        for (String child : children) {
//          staticPaths.add("/" + child);
//        }
//      } catch (IOException ignored) {
//      }
//    }

    String uri = session.getUri();
//    System.out.println(staticPaths);
//    if(staticPaths.contains(uri)) {
      try {
        InputStream in = getClass().getClassLoader().getResourceAsStream("static" + uri);
        if(in == null) throw new IOException("res == null");
        return newChunkedResponse(Response.Status.OK, getContentType(uri), in);
      } catch (IOException e) {
        //if exception thrown just ignore it
      }
//    }
    return null;
  }

  private String getContentType(String uri) {
    String extension = uri.substring(uri.indexOf('.') + 1);
    int questionIndex = extension.indexOf('?');
    if (questionIndex != -1) {
      extension = extension.substring(0, questionIndex);
    }
    switch (extension.toLowerCase()) {
      case "css":
        return "text/css";
      case "js":
        return "application/javascript";
      case "jpg":
      case "jpeg":
        return "image/jpeg";
      case "png":
        return "image/png";
      case "txt":
        return "text/plain";
      default:
        return "application/octet-stream";
    }
  }
}
